package io.jboot.fly.controller;


import com.google.gson.Gson;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.Jboot;
import io.jboot.db.model.Columns;
import io.jboot.fly.Constants;
import io.jboot.fly.FlyConfig;
import io.jboot.fly.model.AttachmentCategory;
import io.jboot.fly.model.Post;
import io.jboot.fly.model.User;
import io.jboot.fly.service.*;
import io.jboot.fly.utils.ElaticSearchUtils;
import io.jboot.fly.utils.EncryptUtils;
import io.jboot.fly.utils.PostType;
import io.jboot.utils.EncryptCookieUtils;
import io.jboot.utils.StringUtils;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.controller.validate.CaptchaValidate;
import io.jboot.web.controller.validate.EmptyValidate;
import io.jboot.web.controller.validate.Form;

import javax.inject.Inject;
import java.util.Date;
import java.util.List;

/**
 * @author fengjr 冯金荣 （fengjinrong@ctsi.com.cn）
 * @version V1.0
 * @Title: 首页的控制器
 */
@RequestMapping(value = "/", viewPath = "/WEB-INF/htmls")
public class IndexController extends JbootController {


    @Inject
    UserService userService;

    @Inject
    PostService postService;

    @Inject
    CategoryService categoryService;

    @Inject
    private CommentService commentService;

    @Inject
    private UserAttachmentService userAttachmentService;
    @Inject
    private AttachmentCategoryService attachmentCategoryService;
    @Inject
    private UserActionService userActionService;



    /**
     * 显示首页
     */
    public void index() {

        //获取关键词
        String keyWord = getPara("keyWord");
        String filter = getPara("2");
        String myselect = getPara("myselect");


        //帖子类型
        String postType = getPara("postType");
        int pageNumber = getParaToInt("page", 1);
        String orderBy=null;
        Integer status=null;
        setAttr("first",2);
        if(postType==null){
            setAttr("postType","0");
        }else{
            setAttr("postType", postType);
        }

        if(!StringUtils.isBlank(postType)&& PostType.WAIT_TO_ANSWERED.getName().equals(postType)){
            status=Post.STATUS_NORMAL;
        }
        if(!StringUtils.isBlank(postType)&& PostType.RESOLVED.getName().equals(postType)){
            status=Post.STATUS_FINISHED;
        }

        if(!StringUtils.isBlank(postType)&& PostType.HIGH_REWARD.getName().equals(postType)){
            orderBy="pay_point";
        }

        Page<Post> postPage= ElaticSearchUtils.searchPost(pageNumber,8,keyWord,"0c275ece74fe4c1fbcaa9d3c7438f1f3",orderBy,status, null);

        if(postPage!=null){
            commentService.join(postPage,"post_id");
            userService.join(postPage, "user_id");
            categoryService.join(postPage, "category_id");
        }
        setAttr("pageData", postPage);
        setAttr("keyWord",keyWord);
        render("index.html");
    }


    public void page() {
        Integer pageNumber = getParaToInt();
        if (pageNumber == null || pageNumber <= 1) {
            redirect("/");
            return;
        }

        Page<Post> postPage = postService.paginate(pageNumber, 20, null, null);
        if (postPage == null || postPage.getPageNumber() > postPage.getTotalPage()) {
            renderError(404);
            return;
        }

        userService.join(postPage, "user_id");
        categoryService.join(postPage, "category_id");
        //userAttachmentService.join(postPage);
        setAttr("pageData", postPage);
        render("page.html");
    }

    public void pageUatc() {
        Integer pageNumber = getParaToInt();
        if (pageNumber == null || pageNumber <= 1) {
            redirect("/");
            return;
        }
        Columns columns = Columns.create();
        String orderBy="created desc";
        columns.ne("userAttachment_id","null");
        Page<Post> postPage = postService.paginateByParams(pageNumber, 20, null, null,columns,orderBy);
        //Page<Post> postPage = postService.paginate(pageNumber, 20, null, null);
        if (postPage == null || postPage.getPageNumber() > postPage.getTotalPage()) {
            renderError(404);
            return;
        }

        userService.join(postPage, "user_id");
        categoryService.join(postPage, "category_id");
        //userAttachmentService.join(postPage);
        setAttr("pageData", postPage);
        render("page.html");
    }


    /**
     * 显示登陆页面
     */
    public void login() {

    }

    /**
     * 进行登录操作
     */
    @EmptyValidate(value = {
            @Form(name = "email", message = "Email不能为空。"),
            @Form(name = "password", message = "密码不能为空。"),
    }, errorRedirect = "/login")
    @CaptchaValidate(form = "vercode", message = "验证码错误", errorRedirect = "/login")
    public void doLogin(String email, String password) {
//        String password1 = getPara("password");

        Ret ret = userService.doLogin(email, password);

        setFlashMap(ret);


        if (ret.isOk()) {
            User user = ret.getAs("user");
            user.setLogged(new Date());
            user.update();

            //发送用户登录 事件
            Jboot.sendEvent(Constants.ACTION_USER_LOGIN, user);

            //保存登录的cookie信息
            EncryptCookieUtils.put(this, Constants.COOKIE_USER_ID, user.getId());
        }

        redirect(ret.isOk() ? "/" : "/login");
    }

    /**
     * 退出登录
     */
    public void logout() {
        removeCookie(Constants.COOKIE_USER_ID);
        redirect("/login");
    }
    public void enjoy() {
        keepPara();
        setAttr("first",1);
        int pageNumber = getParaToInt("page", 1);
        String keyword = getPara("keyword");
        String attachementCategoryId = getPara("attachementCategoryId");
        if(keyword==null){
            setAttr("keyword", keyword);
        }
        Integer userAttachementType=null;
        if(attachementCategoryId==null||"0".equals(attachementCategoryId)){
            setAttr("attachementCategoryId", "0");
            userAttachementType=null;
        }else{
            setAttr("attachementCategoryId", attachementCategoryId);
            userAttachementType=Integer.parseInt(attachementCategoryId);
        }


        String orderBy="created desc";
        Page<Post> postPage;
        postPage=ElaticSearchUtils.searchPost(pageNumber,8,keyword,"7796fa78031a4b3988d6bc5a629041f3",null,null,userAttachementType);
        commentService.join(postPage,"post_id");

        userService.join(postPage, "user_id");
        categoryService.join(postPage, "category_id");
        userAttachmentService.join(postPage,"userAttachment_id");
        attachmentCategoryService.join(postPage,"userAttachement_type");

        setAttr("pageData", postPage);
        render("enjoy.html");
    }
    public void bufferEnjoy(String attachementCategoryId) {
        keepPara();
        int pageNumber = getParaToInt("page", 1);
        List<AttachmentCategory> attachementCategorys = attachmentCategoryService.findAll();
        setAttr("attachementCategorys", attachementCategorys);
        String keyword = getPara("keyword");
        if(keyword==null){

            setAttr("keyword", keyword);
        }
        Columns columns = Columns.create();
        String orderBy="created desc";
        columns.ne("userAttachment_id","null");
        Page<Post> postPage;
//        if(attachementCategoryId!=null){
//            columns.eq("userAttachement_type",attachementCategoryId);
//            postPage = postService.paginateByParams(pageNumber, 2, null, null,columns,orderBy);
//        }else {
//            postPage = postService.paginateByParams(pageNumber, 2, null, null, columns, orderBy);
//        }
        postPage=ElaticSearchUtils.searchPost(pageNumber,8,keyword,"7796fa78031a4b3988d6bc5a629041f3",null,null, null);
        commentService.join(postPage,"post_id");

        userService.join(postPage, "user_id");
        categoryService.join(postPage, "category_id");
        userAttachmentService.join(postPage,"userAttachment_id");
        attachmentCategoryService.join(postPage,"userAttachement_type");
        renderText(new Gson().toJson(postPage));
    }
    public void share() {

    }
    /**
     * 注册页面
     */
    public void register() {

    }
    public void input_search() {

    }

    /**
     * 进行注册操作
     */
    @EmptyValidate(value = {
            @Form(name = "email", message = "Email不能为空。"),
            @Form(name = "nickname", message = "昵称不能为空。"),
            @Form(name = "password", message = "密码不能为空。"),
            @Form(name = "repassword", message = "确认密码不能为空。"),
    }, errorRedirect = "/register")
    @CaptchaValidate(form = "vercode", message = "验证码错误", errorRedirect = "/regsiter")
    public void doRegister(String email, String nickname, String password, String repassword) {

        if (!password.equals(repassword)) {
            setFlashAttr("message", "密码为空 或 两次输入密码不相等");
            redirect("/register");
            return;
        }

        User user = userService.findByEmail(email);
        if (user != null) {
            setFlashAttr("message", "该邮箱已经存在");
            redirect("/register");
            return;
        }

        user = new User();
        user.setEmail(email);
        user.setNickname(nickname);
        user.setPoint((long) FlyConfig.get().getInitPoint());
//        user.setStatus(User.STATUS_AUDITING); //审核中
        //不再进行审核，可直接登录使用
        user.setStatus(User.STATUS_NORMAL);

        String salt = EncryptUtils.generateSalt();
        String encryptPassword = EncryptUtils.encryptPassword(password, salt);

        user.setSalt(salt);
        user.setPassword(encryptPassword);

        boolean success = userService.save(user);
        if (success) {
            setFlashAttr("message", "用户注册成功！请登录。");
            redirect("/active");
        } else {
            setFlashAttr("message", "系统错误，请联系管理员。");
            redirect("/register");
        }

    }


    /**
     * 回去密码页面
     */
    public void getpwd() {

    }
    /*下载*/
    public void content() {

    }
    /*排行榜*/
    public void ranklist() {

        setAttr("first",3);


    }
    /**
     * 进行取回密码操作
     */
    public void doGetpwd() {

    }

    public void captcha() {
        renderCaptcha();
    }


    /**
     * 需要激活
     */
    public void active() {

    }


}
